// pages/bulk-materials-category/bulk-materials-category.ts
import { productCategories } from '../../../config/product-categories';
import { goToPage, PAGE_PRODUCT_LIST_MATERIAL } from '../../../config/pages';
import util from '../../../utils/util';

interface PageData {
  currentCategory: string;
  scrollTop: number;
  scrollIntoView: string;
  searchKeyword: string;
  materialData: Array<{
    key: string;
    name: string;
    materials: string[];
  }>;
}

interface PageInstance {
  data: PageData;
  scrollUpdateHandler?: () => void;
  [key: string]: any;
}

// 生成 key：将分类名称转换为 key
function generateKey(name: string): string {
  const keyMap: Record<string, string> = {
    '单面胶带': 'single-tape',
    '双面胶带': 'double-tape',
    '保护膜': 'protective-film',
    '电磁屏蔽材料': 'magnetic-material',
    '吸波材料': 'absorption-material',
    '光学材料': 'optical-material',
    '声学材料': 'acoustic-material',
    '标签材料': 'label-material',
    '热界面材料': 'thermal-material',
    '薄膜': 'thin-film',
    '泡棉': 'foam',
    '模切辅料': 'die-cut',
    '皮肤胶带': 'leather-tape',
    '绝缘纸': 'insulation-paper'
  };
  return keyMap[name] || name.toLowerCase().replace(/\s+/g, '-');
}

// 转换 productCategories 数据格式
const materialData = productCategories.map(category => ({
  key: generateKey(category.name),
  name: category.name,
  materials: category.products
}));

const pageInstance: PageInstance = {
  data: {
    // 当前选中的分类
    currentCategory: materialData[0]?.key || '' as string,
    
    // 滚动位置
    scrollTop: 0,
    
    // 滚动到指定元素
    scrollIntoView: '',
    
    // 搜索关键词
    searchKeyword: '',
    
    // 材料分类数据（从 productCategories 获取）
    materialData: materialData,
  },

  onLoad(options: any) {
    console.log('散料分类页面加载完成');
    
    // 检查URL参数，确定初始分类
    if (options.category) {
      this.setData({
        currentCategory: options.category
      });
    }
    
    // 初始化滚动监听
    this.initScrollListener();
  },

  onShow() {
    console.log('散料分类页面显示');
  },

  // 切换分类
  switchCategory(e: any) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.currentCategory) return;
    
    this.setData({
      currentCategory: category
    });
    
    // 滚动到对应分类区域
    this.scrollToCategory(category);
  },

  // 滚动事件处理
  onScroll() {
    if (this.scrollUpdateHandler) {
      this.scrollUpdateHandler();
    }
  },



  // 初始化滚动监听
  initScrollListener() {
    // 使用更精确的滚动监听，参考HTML原型的实现
    this.observeScroll();
  },

  // 监听右侧滚动，更新左侧选中状态
  observeScroll() {
    // 使用节流函数避免频繁更新
    let scrollTimer: any = null;
    
    const updateActiveCategory = () => {
      if (scrollTimer) {
        clearTimeout(scrollTimer);
      }
      
      scrollTimer = setTimeout(() => {
        const query = wx.createSelectorQuery();
        query.select('#materialsContent').scrollOffset();
        query.select('#materialsContent').boundingClientRect();
        query.exec((res) => {
          if (res[0] && res[1]) {
            const scrollTop = res[0].scrollTop;
            const containerHeight = res[1].height;
            const viewportCenter = scrollTop + containerHeight / 3; // 使用1/3位置作为判断点
            
            // 检查每个分类区域的位置
            const categoryQueries = this.data.materialData.map((item: any) => {
              return new Promise((resolve) => {
                const categoryQuery = wx.createSelectorQuery();
                categoryQuery.select(`#category-${item.key}`).boundingClientRect();
                categoryQuery.select('#materialsContent').boundingClientRect();
                categoryQuery.exec((categoryRes) => {
                  if (categoryRes[0] && categoryRes[1]) {
                    const categoryRect = categoryRes[0];
                    const containerRect = categoryRes[1];
                    const categoryTop = categoryRect.top - containerRect.top + scrollTop;
                    const categoryBottom = categoryTop + categoryRect.height;
                    
                    // 判断分类是否在视口上方1/3处
                    const isVisible = viewportCenter >= categoryTop && viewportCenter <= categoryBottom;
                    resolve({
                      key: item.key,
                      isVisible: isVisible,
                      distance: Math.abs(viewportCenter - (categoryTop + categoryRect.height / 2))
                    });
                  } else {
                    resolve({ key: item.key, isVisible: false, distance: Infinity });
                  }
                });
              });
            });
            
            Promise.all(categoryQueries).then((results: any[]) => {
              // 找到最接近视口中心的可见分类
              const visibleCategories = results.filter(result => result.isVisible);
              if (visibleCategories.length > 0) {
                const activeCategory = visibleCategories.sort((a, b) => a.distance - b.distance)[0];
                if (activeCategory && activeCategory.key !== this.data.currentCategory) {
                  this.setData({
                    currentCategory: activeCategory.key
                  });
                }
              }
            });
          }
        });
      }, 50); // 50ms节流
    };
    
    // 绑定滚动事件
    this.scrollUpdateHandler = updateActiveCategory;
  },

  // 滚动到指定分类
  scrollToCategory(category: string) {
    console.log('滚动到分类:', category);
    
    // 使用更简单的方法，直接使用scroll-view的scroll-into-view属性
    this.setData({
      scrollIntoView: `category-${category}`
    });
    
    // 延迟重置scrollIntoView，避免影响后续滚动
    setTimeout(() => {
      this.setData({
        scrollIntoView: ''
      });
    }, 500);
  },

  // 查看材料详情
  viewMaterial(e: any) {
    const materialName = e.currentTarget.dataset.name;
    console.log('查看材料详情:', materialName);
    
    // 跳转到材料一览页面，并携带材料名称作为搜索关键词
    goToPage(PAGE_PRODUCT_LIST_MATERIAL, { keyword: materialName });
  },

  // 广告点击事件
  goToAd() {
    // 跳转到咨询页面
    goToPage('/pages/consultation/consultation', { type: 'bulk' });
  },

  // 搜索输入事件
  onSearchInput(e: any) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认事件
  onSearchConfirm(e: any) {
    const keyword = e.detail.value.trim();
    if (keyword) {
      this.performSearch(keyword);
    }
  },

  // 执行搜索
  performSearch(keyword: string) {
    console.log('搜索关键词:', keyword);
    
    // 跳转到材料一览页面，并携带搜索关键词
    goToPage(PAGE_PRODUCT_LIST_MATERIAL, { keyword: keyword });
  },

  // 搜索框Banner链接点击事件
  onSearchBannerLinkTap(e: any) {
    const { linkUrl } = e.detail;
    console.log('搜索框Banner链接点击:', linkUrl);
    util.navigateToAdLink(linkUrl);
  },

  // 材料Banner链接点击事件
  onMaterialsBannerLinkTap(e: any) {
    const { linkUrl } = e.detail;
    console.log('材料Banner链接点击:', linkUrl);
    util.navigateToAdLink(linkUrl);
  }
};

Page(pageInstance);
